package com.cmw.auntapp.ui;


import android.Manifest;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.R;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.FormUtil;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.core.util.StringHandler;
import com.cmw.auntapp.core.util.ToastAlert;
import com.cmw.auntapp.model.LocationModel;
import com.cmw.auntapp.presenter.OrderPresenter;
import com.cretin.www.externalmaputilslibrary.OpenExternalMapAppUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static com.cmw.auntapp.R2.id.tv_address_val;
import static com.cmw.auntapp.R2.id.tv_cname_val;
import static com.cmw.auntapp.R2.id.tv_code_val;
import static com.cmw.auntapp.R2.id.tv_down_time_val;
import static com.cmw.auntapp.R2.id.tv_tel_val;
import static com.cmw.auntapp.R2.id.tv_up_time_val;
import static com.cmw.auntapp.constant.Constant.AUNT_LOCATION_KEY;
import static com.cmw.auntapp.constant.Constant.ORDER_XSTATUS_SERVICE_IN;
import static com.cmw.auntapp.constant.Constant.ORDER_XSTATUS_SERVIE_OK;

/**
 * 订单详情服务中/服务完成Activity
 *
 * @Auth chengmingwei
 * @date 2021-04-05 16:48
 */
public class OrderServiceActivity extends BaseActivity {

    @BindView(R.id.tv_service_orders)
    TextView tvServiceOrders;

    @BindView(R.id.vw_defaultStatus)
    View vwDefaultStatus;

    @BindView(R.id.pb_orderStatus)
    View pbOrderStatus;

    @BindView(R.id.btn_service_order)
    ImageButton btnServiceOrder;

    @BindView(R.id.tv_down_time_label)
    TextView tvDownTimeLabel;

    @BindView(R.id.tv_down_time_val)
    TextView tvDownTimeVal;

    private OrderPresenter orderPresenter;

    private JSONObject orderData; //订单数据

    private static final long TIMEOUT_MILLS = 1000L; //

    private long seconds = 0l;

    private boolean serviceFinishFlag = false; // 是否完成服务

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case 9999 :{
                    if (serviceFinishFlag) {
                        return;
                    }
                    makeServiceDoing();
                    updateTime();
                    sendRoundTime(what);
                    break;
                }
            }
        }
    };

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_order_service;
    }

    @Override
    void onInit(Bundle savedInstanceState) {
        setTitle(R.string.order_detail_title);
        AssetManager assets = getAssets();
        Typeface fromAsset = Typeface.createFromAsset(assets, "fonts/dfbudingw12_gb.ttf");
        tvServiceOrders.setTypeface(fromAsset);
        orderPresenter = new OrderPresenter(this);
        checkPermissionRequest();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
        loadData();
    }

    private void loadData() {
        String orderId = getOrderId();
        orderPresenter.get(orderId);
    }

    private String getOrderId() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        return bundle.getString("orderId");
    }

    public void checkPermissionRequest() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.e(TAG, "找打电话权限申请："+(aBoolean ? "成功" : "失败"));
            }
        });
    }

    /**
     * 地址导航
     * see: https://github.com/MZCretin/ExternalMapUtils 导航使用说明(须安装高德或百度)
     * @param view
     */
    @OnClick(R.id.btn_navigation_map)
    public void doNavigation(View view) {
        Log.w(TAG,"doNavigation . 地址导航...");
        if (!checkDataReady()) {
            return;
        }
        SharedPreferencesUtil util = SharedPreferencesUtil.getInstance(this);
        LocationModel locationModel = util.getObject(AUNT_LOCATION_KEY, LocationModel.class);
        String anchor = locationModel.getAnchor();
        String sourceLongitude = locationModel.getLongitude().toString();
        String sourceLatitude = locationModel.getLatitude().toString();
        //B.longitude,B.latitude
        String longitude = orderData.getString("longitude");
        String latitude = orderData.getString("latitude");
        String address = orderData.getString("address");
        String appName = getResources().getString(R.string.app_name);

        //
        OpenExternalMapAppUtils.openMapDirection(this, sourceLongitude, sourceLatitude, anchor,
                longitude, latitude, address, appName);

        //打开app端导航 使用高德和百度
        OpenExternalMapAppUtils.openMapNavi(this, longitude, latitude, address, address, appName);
    }

    /**
     * 打电话
     * @param view
     */
    @OnClick(R.id.btn_call_tel)
    public void doCallTel(View view) {
        Log.w(TAG,"doCallTel . 打电话...");
        if (!checkDataReady()) {
            return;
        }
        String phoneNum = orderData.getString("compnayTel");
        phoneNum = phoneNum.replace("-", "");
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    private boolean checkDataReady() {
        if (null == orderData || orderData.isEmpty()) {
            ToastAlert.showMsg("数据环境还未准备好，请稍后再重新尝试打开当前页面！");
            return false;
        }
        return true;
    }

    /**
     * 下钟/服务完成
     * @param view
     */
    @OnClick(R.id.btn_service_order)
    public void doServiceOrder(View view) {
        if (!serviceFinishFlag) {
            Log.w(TAG,"doOnWork . 下钟...");
            String orderId = getOrderId();
            ToastAlert.confirm(this, "下钟提醒", "您确定要开始下钟吗？", (actionBtn)->{
                if (actionBtn.equals(ToastAlert.ACTIONBTN_CANCEL)) {
                    return;
                }
                orderPresenter.updateXstatus(orderId, ORDER_XSTATUS_SERVIE_OK+"");
            });

        } else {
            go(MainActivity.class); // 跳转到首页抢单
        }
    }

    /**
     * 我的 -> 跳转到用户中心
     */
    @OnClick(R.id.iv_my_center)
    public void doGoUserCenter(View view){
        boolean isLogin = orderPresenter.isLogin();
        if (!isLogin) {
            go(LoginActivity.class);
            return;
        }
        Constant.userCenterBackActivity = this.getClass();
        go(UserCenterActivity.class);
    }

    @Override
    protected boolean doFailure(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case GET:{ //订单详情数据

                break;
            } case PUT:{ // 上钟/下钟切换失败
                goDetailPage(dataResult);
                break;
            }
        }
        return true;
    }

    private void goDetailPage(DataResult dataResult) {
        Integer code = dataResult.getCode();
        String msg = dataResult.getMsg();
        boolean success = dataResult.isSuccess();
        if (success) {
            return;
        }
        ToastAlert.showMsg(msg);
        if (code == 40001) { // 在下钟前检测到，客户将订单取消了，则跳转到详情页面
            String orderId = getOrderId();
            Map<String, String> params = new HashMap<>();
            params.put("orderId", orderId);
            go(OrderDetailActivity.class, params);
        }
    }

    @Override
    protected boolean doSuccess(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case GET:{ //订单详情数据
                orderData = (JSONObject)dataResult.getDatas();
                setValues();
                break;
            }case PUT:{ // 下钟成功后回调
                loadData(); // 重新加载订单数据
                break;
            }
        }
        return true;
    }

    /**
     * 为页面元素赋值
     */
    private void setValues() {
        int[] viewIds = new int[]{tv_code_val,tv_cname_val,tv_address_val,tv_tel_val,tv_up_time_val,tv_down_time_val};
        FormUtil.setValues(this, orderData, viewIds);
        Integer xstatus = orderData.getInteger("xstatus");
        if (null == xstatus) {
            return;
        }
        if (xstatus.intValue() == Constant.ORDER_XSTATUS_SERVICE_IN) { // 服务中,开始计算时间
            serviceFinishFlag = false;
            makeServiceDoing();
            sendRoundTime(9999);
        }

        if (xstatus.intValue() == ORDER_XSTATUS_SERVIE_OK) { // 服务完成
            makeServiceFinish();
        }
    }



    /**
     * 服务中
     */
    private void makeServiceDoing() {
        Date startTime = orderData.getDate("startTime");
        Date today = orderData.getDate("today");
        if (null == startTime) {
            startTime = today;
        }
        Date deviceTodayTime = new Date();
//        if (deviceTodayTime.compareTo(today) < 0) {
//            ToastAlert.showMsg("你当前使用的手机时间不正确，请将手机时间调整正确!");
//            return;
//        }
        long resultTime = deviceTodayTime.getTime() - startTime.getTime();
        seconds = resultTime / 1000;
    }

    private void updateTime() {
        String txt = getResources().getString(R.string.order_detail_btn_service_doing_temp);
        int minutes = (int)(seconds / 60);
        int currSeconds = (int)(seconds - (minutes * 60));
        String minutesStr = (minutes < 10) ? "0"+minutes : minutes+"";
        String currSecondsStr = (currSeconds < 10) ? "0"+currSeconds : currSeconds+"";
        String upTimeStr = StringHandler.formatStr(txt, minutesStr+":"+currSecondsStr);
        tvServiceOrders.setText(upTimeStr);
    }

    /**
     * 服务完成
     */
    private void makeServiceFinish() {
        serviceFinishFlag = true;
        tvDownTimeVal.setVisibility(View.VISIBLE);
        tvDownTimeLabel.setVisibility(View.VISIBLE);
        pbOrderStatus.setVisibility(View.INVISIBLE);
        vwDefaultStatus.setVisibility(View.VISIBLE);
        btnServiceOrder.setImageResource(R.drawable.btn_service_ok);
        String txt = getResources().getString(R.string.order_detail_btn_service_ok_temp);
        int minutes = orderData.getInteger("serviceTime");
        String minutesStr = (minutes < 10) ? "0"+minutes : minutes+"";
        String upTimeStr = StringHandler.formatStr(txt, minutesStr+":00");
        tvServiceOrders.setText(upTimeStr);
    }

    /**
     * 定时轮询进行分：秒计数
     * @param what
     */
    private void sendRoundTime(int what) {
        Message newMsg = new Message();
        newMsg.what = what;
        handler.sendMessageDelayed(newMsg, 1000);
    }


    public void cancel(){
        if (null == handler) return;
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancel();
    }
}